<?php
if(!function_exists('admin_url')){
	function admin_url($router = null,$routeParams = null){
		$CI =& get_instance();
		$p = explode('/',$router);
		
		$controller = (isset($p[1])?$p[1]:null);
		$action = (isset($p[2])?$p[2]:null);
		
		$secret = array($CI->config->item('secret_name')=>get_secret_key($controller,$action));
		
		if (is_array($routeParams)){
			$params = array_merge($routeParams,$secret);
		}else{
			$params = $secret;
		}
		return create_url($router,$params);
	}
}
if ( ! function_exists('current_admin_url'))
{
	function current_admin_url()
	{
		$CI =& get_instance();
		return rtrim($CI->config->site_url($CI->uri->uri_string()),$CI->config->item('url_suffix'));
	}
}

if (!function_exists("get_secret_key")){
	/**
     * Generate secret key for controller and action based on form key
     *
     * @param string $controller Controller name
     * @param string $action Action name
     * @return string
     */
	function get_secret_key($controller = null, $action = null){
		$CI =& get_instance();
		$CI->load->library('encrypt');
		$salt = getCsrfToken();
		if (!$controller){
			$controller = $CI->router->fetch_class();
		}
		if (!$action){
			$action = $CI->router->fetch_method();
		}
		$secret = $controller.$action.$salt;
		return $CI->encrypt->get_hash($secret);
	}
}

if (!function_exists("create_url")){
	function create_url($uri='',$params = array()){
		$CI =& get_instance();
		return $CI->router->get_url($uri,$params);
	}
}

if (!function_exists("get_url")){
	function get_url($uri='',$params = array()){
		$CI =& get_instance();
		$url = $CI->config->site_url($uri);
		
		$query_params = null;
		if (isset($params['query'])){
			 $query_params = $params['query'];
		}
		
		$query = null;
		
		if ($query_params !== null){
			if (is_string($query_params)){
				$query = $query_params;
			}elseif (is_array($query_params)){
				ksort($query_params);
				$query = http_build_query($query_params,'','&');
			}
		}
		
		if ($query !== null){
			 $mark = (strpos($url, '?') === false) ? '?' : '&';
             $url .= $mark . $query;
		}
		
		if (isset($params['fragment'])){
			$url .='#'.$params['fragment'];
		}
		return $url;
	}
}
